package com.yubb.platform.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yubb.common.constant.Constants;
import com.yubb.common.constant.UserConstants;
import com.yubb.common.core.domain.Ztree;
import com.yubb.common.core.domain.platform.PlatformMenu;
import com.yubb.common.core.domain.platform.PlatformUser;
import com.yubb.common.core.domain.platform.dto.PlatformMenuDTO;
import com.yubb.common.core.domain.platform.dto.PlatformRoleDTO;
import com.yubb.common.core.domain.platform.dto.PlatformUserDTO;
import com.yubb.common.core.domain.platform.vo.PlatformMenuVO;
import com.yubb.common.core.domain.platform.vo.PlatformUserVO;
import com.yubb.common.utils.StringUtils;
import com.yubb.common.utils.bean.DozerUtils;
import com.yubb.platform.domain.PlatformRoleMenu;
import com.yubb.platform.mapper.PlatformMenuMapper;
import com.yubb.platform.mapper.PlatformRoleMenuMapper;
import com.yubb.platform.mapper.PlatformUserMapper;
import com.yubb.platform.service.IPlatformMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.MessageFormat;
import java.util.*;

/**
 * @Description 平台菜单接口实现
 * @Author zhushuyong
 * @Date 2021/7/15 22:39
 * @since:
 * @copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 * GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Slf4j
@Service
public class PlatformMenuServiceImpl extends ServiceImpl<PlatformMenuMapper, PlatformMenu> implements IPlatformMenuService {

    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private PlatformMenuMapper menuMapper;

    @Autowired
    private PlatformRoleMenuMapper roleMenuMapper;

    @Autowired
    private PlatformUserMapper platformUserMapper;

    /**
     * 根据用户查询菜单
     *
     * @param user 用户信息
     * @return 菜单列表
     */
    @Override
    public List<PlatformMenuVO> selectMenusByUser(PlatformUserDTO user)
    {
        List<PlatformMenuVO> menus = new LinkedList<PlatformMenuVO>();
        // 租户管理员显示所有菜单信息
        if (DozerUtils.copyProperties(user, PlatformUser.class).isAdmin())
        {
            menus = menuMapper.selectMenuNormalAll();
        }
        else
        {
            menus = menuMapper.selectMenusByUserId(user.getId());
        }
        return getChildPerms(menus, Constants.PARENT_MENU_ID);
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<PlatformMenuVO> selectMenuList(PlatformMenuDTO menu, String userId)
    {
        List<PlatformMenuVO> menuList = null;
        PlatformUser platformUser = platformUserMapper.selectById(userId);
        if (PlatformUser.isAdmin(platformUser.getUserType())) {
            menuList = menuMapper.selectMenuList(menu);
        } else {
            menu.getParams().put("userId", userId);
            menuList = menuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    /**
     * 查询菜单集合
     *
     * @return 所有菜单信息
     */
    @Override
    public List<PlatformMenuVO> selectMenuAll(String userId)
    {
        List<PlatformMenuVO> menuList = null;
        PlatformUser platformUser = platformUserMapper.selectById(userId);
        if (PlatformUser.isAdmin(platformUser.getUserType()))
        {
            menuList = menuMapper.selectMenuAll();
        }
        else
        {
            menuList = menuMapper.selectMenuAllByUserId(userId);
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户id
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByUserId(String userId)
    {
        List<String> perms = menuMapper.selectPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询菜单
     *
     * @param role 角色对象
     * @return 菜单列表
     */
    @Override
    public List<Ztree> roleMenuTreeData(PlatformRoleDTO role, String userId)
    {
        String roleId = role.getId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<PlatformMenuVO> menuList = selectMenuAll(userId);
        if (StringUtils.isNotNull(roleId))
        {
            List<String> roleMenuList = menuMapper.selectMenuTree(roleId);
            ztrees = initZtree(menuList, roleMenuList, true);
        }
        else
        {
            ztrees = initZtree(menuList, null, true);
        }
        return ztrees;
    }

    /**
     * 查询所有菜单
     *
     * @return 菜单列表
     */
    @Override
    public List<Ztree> menuTreeData(String userId)
    {
        List<PlatformMenuVO> menuList = selectMenuAll(userId);
        List<Ztree> ztrees = initZtree(menuList);
        return ztrees;
    }

    /**
     * 查询系统所有权限
     *
     * @return 权限列表
     */
    @Override
    public LinkedHashMap<String, String> selectPermsAll(String userId)
    {
        LinkedHashMap<String, String> section = new LinkedHashMap<>();
        List<PlatformMenuVO> permissions = selectMenuAll(userId);
        if (StringUtils.isNotEmpty(permissions))
        {
            for (PlatformMenuVO menu : permissions)
            {
                section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
            }
        }
        return section;
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<PlatformMenuVO> menuList)
    {
        return initZtree(menuList, null, false);
    }

    /**
     * 对象转菜单树
     *
     * @param menuList 菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag 是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<PlatformMenuVO> menuList, List<String> roleMenuList, boolean permsFlag)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (PlatformMenuVO menu : menuList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getId());
            ztree.setpId(menu.getParentId());
            ztree.setName(transMenuName(menu, permsFlag));
            ztree.setTitle(menu.getMenuName());
            if (isCheck)
            {
                ztree.setChecked(roleMenuList.contains(menu.getId() + menu.getPerms()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public String transMenuName(PlatformMenuVO menu, boolean permsFlag)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(menu.getMenuName());
        if (permsFlag)
        {
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
        }
        return sb.toString();
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(String menuId)
    {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public PlatformMenuVO selectMenuById(String menuId)
    {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 查询子菜单数量
     *
     * @param parentId 父级菜单ID
     * @return 结果
     */
    @Override
    public long selectCountMenuByParentId(String parentId)
    {
        return menuMapper.selectCount(Wrappers.query(PlatformMenu.builder().parentId(parentId).build()));
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public long selectCountRoleMenuByMenuId(String menuId)
    {
        return roleMenuMapper.selectCount(Wrappers.query(PlatformRoleMenu.builder().menuId(menuId).build()));
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(PlatformMenuDTO menu)
    {
        return menuMapper.insert(DozerUtils.copyProperties(menu, PlatformMenu.class));
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(PlatformMenuDTO menu)
    {
        return menuMapper.updateById(DozerUtils.copyProperties(menu, PlatformMenu.class));
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(PlatformMenuDTO menu)
    {
        String menuId = StringUtils.isIdNull(menu.getId());
        Optional<PlatformMenu> info = menuMapper.selectList(Wrappers.query(PlatformMenu.builder()
                .menuName(menu.getMenuName()).parentId(menu.getParentId()).build())).stream().findFirst();
        if (info.isPresent() && !menuId.equals(info.get().getId()))
        {
            return UserConstants.MENU_NAME_NOT_UNIQUE;
        }
        return UserConstants.MENU_NAME_UNIQUE;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<PlatformMenuVO> getChildPerms(List<PlatformMenuVO> list, String parentId)
    {
        List<PlatformMenuVO> returnList = new ArrayList<PlatformMenuVO>();
        for (Iterator<PlatformMenuVO> iterator = list.iterator(); iterator.hasNext();)
        {
            PlatformMenuVO t = (PlatformMenuVO) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (parentId.equals(t.getParentId()))
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<PlatformMenuVO> list, PlatformMenuVO t)
    {
        // 得到子节点列表
        List<PlatformMenuVO> childList = getChildList(list, t);
        t.setChildren(childList);
        for (PlatformMenuVO tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<PlatformMenuVO> getChildList(List<PlatformMenuVO> list, PlatformMenuVO t)
    {
        List<PlatformMenuVO> tlist = new ArrayList<PlatformMenuVO>();
        Iterator<PlatformMenuVO> it = list.iterator();
        while (it.hasNext())
        {
            PlatformMenuVO n = (PlatformMenuVO) it.next();
            if (n.getParentId().equals(t.getId()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<PlatformMenuVO> list, PlatformMenuVO t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
